<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of UserModel
 *
 * @author John
 */
namespace Admin\Model;
use Think\Model\RelationModel;

class UserModel extends RelationModel {

    protected $_validate = array(
        array('userName','require','字段名称必填'),
        array('mobile','','手机号重复',0,'unique',3)
    );
    
    protected $_auto = array(
        array("addtime",'time',1,'function'),
        array('password','',2,'ignore'),
    );

    protected $_link = array(
        'Role' => array(
            'mapping_type'          => self::MANY_TO_MANY,
            'class_name'            => 'Role',
            'foreign_key'           => 'user_id',
            'relation_foreign_key'  => 'role_id',
            'relation_table'        => 'zh_role_user',
        ),
    );
    

    public function deleteUser($uid){
        $ids = explode(",", $uid);
        foreach ($ids as $id) {
            $this->startTrans();
            D("RoleUser")->where(array("user_id" => $id))->delete();
            $ret = $this->where(array("id" => $id))->delete();
            $this->commit();
        }
    }
    
    public function addUser($model){
        
        $role_user_db = D("RoleUser");
        if($model['id']){
            $uid = $model['id'];
            $this->data($model)->save();
        }else{
            $uid = $this->data($model)->add();
        }
        $role_user_db->where(array('user_id' => $uid))->delete();
        $role_id = I("post.role_id",0,"intval");

        //此处一个用户只有一个角色
        if($role_id){
            $role_user_db->data(array('user_id' => $uid,'role_id',$role_id))->add();
        }
    }

    public function _before_write(&$data)
    {
        parent::_before_write($data); // TODO: Change the autogenerated stub
        if($data['password']){
            $data['password']=md5($data['password']);
        }
    }
}
